package site.xuxingcan.xposedxiwang;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.gson.Gson;

import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.callbacks.XC_LoadPackage;

import static de.robv.android.xposed.XposedHelpers.callMethod;
import static de.robv.android.xposed.XposedHelpers.callStaticMethod;
import static de.robv.android.xposed.XposedHelpers.findAndHookMethod;
import static de.robv.android.xposed.XposedHelpers.findClass;

/**
 * Created by xuxingcan on 16-10-23.
 */
public class XposedInit implements IXposedHookLoadPackage {
    public static Context mSystemContext;
    private Class<?> mModleClass;
    private Class<?> mModelMultiClassh;
    private Activity mActivity;
    private Context mContext;
    private Handler mHandler;
    private Socket socket;
    private SocketHelper socketHelper;
    private Gson gson = new Gson();
    private ExecutorService fixedThreadPool;

    @Override
    public void handleLoadPackage(XC_LoadPackage.LoadPackageParam loadPackageParam) throws Throwable {
        String packageName = loadPackageParam.packageName;
        if (!packageName.equalsIgnoreCase("com.xiwang")) {
            return;
        }
        try {
            Object activityThread = callStaticMethod(findClass("android.app.ActivityThread", null), "currentActivityThread");
            mSystemContext = (Context) callMethod(activityThread, "getSystemContext");
            try {
                String versionName = mSystemContext.getPackageManager().getPackageInfo(packageName, 0).versionName;
                XposedBridge.log("Loaded app: " + loadPackageParam.packageName + " " + versionName);
            } catch (Exception e) {
                XposedBridge.log(e);
            }
            try {
                hookMessageAdapter(loadPackageParam.classLoader);
            } catch (Exception e) {
                XposedBridge.log(e);
            }
            fixedThreadPool = Executors.newFixedThreadPool(3);
//            new Timer().schedule(new TimerTask() {
//                @Override
//                public void run() {
//                    try {
//                        if (isServerClose(socket)) {
//                            socket = new Socket(getIP(), 8191);
//                            socketHelper = new SocketHelper(socket);
//                        }
//                        Model model = new Model();
//                        model.msg = "heartBeat";
//                        socketHelper.writeLineAndFlush(gson.toJson(model));
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
//            }, 60 * 1000, 60 * 1000);
        } catch (Exception e) {
            XposedBridge.log(e);
        }
    }

    private void hookMessageAdapter(final ClassLoader loader) {
        findAndHookMethod("com.xiwang.activity.OrderTenderActivity", loader, "onCreate", Bundle.class, new XC_MethodHook() {
            @Override
            protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                super.afterHookedMethod(param);
                XposedBridge.log("afterHookedMethod");
                mHandler = new Handler(Looper.getMainLooper());
                mActivity = (Activity) param.thisObject;
                mContext = (Context) param.thisObject;
                fixedThreadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            socket = new Socket(getIP(), 8191);
                            socketHelper = new SocketHelper(socket);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
        findAndHookMethod("com.xiwang.activity.OrderTenderActivity", loader, "onDestroy", new XC_MethodHook() {
            @Override
            protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                super.afterHookedMethod(param);
                fixedThreadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            socket.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
        findAndHookMethod("com.xiwang.activity.OrderTenderActivity$MessageAdapter", loader, "getView", int.class, View.class, ViewGroup.class, new XC_MethodHook() {
            @Override
            protected void afterHookedMethod(final MethodHookParam param) throws Throwable {
                super.afterHookedMethod(param);
                XposedBridge.log("OrderTenderActivity$MessageAdapter afterHookedMethod");
                ((View) param.args[1]).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        XposedBridge.log("onClick");
                        final Object dMessage = callMethod(param.thisObject, "getItem", ((int) param.args[0]));
                        final String shipmentCode = (String) callMethod(dMessage, "getShipmentCode");
                        final String zbShipmentId = String.valueOf(callMethod(dMessage, "getZbShipmentId"));
                        final Class<?> DataCacheClass = findClass("com.xiwang.adapter.DataCache", loader);
                        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);  //先得到构造器
                        builder.setTitle("信息"); //设置标题
                        builder.setMessage("调度单号：" + shipmentCode + "\n确定抢该单吗？"); //设置内容
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { //设置确定按钮
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                long time = ((Long) callMethod(dMessage, "getTenderInterval")).longValue();
                                if (time < 0) {
                                    time = 1;
                                }
                                Toast.makeText(mActivity, "调度单号：" + shipmentCode + "\n剩余时间：" + time, Toast.LENGTH_LONG).show();
                                final long finalTime = time;
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            Thread.sleep(finalTime);
                                            final String result = (String) callStaticMethod(findClass("com.xiwang.adapter.DataCache", loader), "orderTenderConfirm", zbShipmentId);
                                            mHandler.post(new Runnable() {
                                                @Override
                                                public void run() {
                                                    Toast.makeText(mActivity, "调度单号：" + shipmentCode + "\n已执行抢单", Toast.LENGTH_LONG).show();
                                                }
                                            });
                                        } catch (final Exception e) {
                                            XposedBridge.log(e);
                                            mHandler.post(new Runnable() {
                                                @Override
                                                public void run() {
                                                    Toast.makeText(mActivity, "调度单号：" + shipmentCode + "\n抢单失败:" + e.getMessage(), Toast.LENGTH_LONG).show();
                                                }
                                            });
                                        }
                                    }
                                }).start();
                            }
                        });
                        builder.setNeutralButton("立即抢单", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        final String result = (String) callStaticMethod(findClass("com.xiwang.adapter.DataCache", loader), "orderTenderConfirm", zbShipmentId);
                                        mHandler.post(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(mActivity, "调度单号：" + shipmentCode + "\n" + result, Toast.LENGTH_LONG).show();
                                            }
                                        });
                                    }
                                }).start();
                            }
                        });
                        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { //设置取消按钮
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
//                                Object toast = callStaticMethod(findClass("android.widget.Toast", loader), "makeText", mContext, "4123", Toast.LENGTH_SHORT);
//                                callMethod(toast, "show");
                            }
                        });
                        builder.setCancelable(false);
                        builder.create().show();
                    }
                });
            }
        });
    }

    public Boolean isServerClose(Socket socket) {
        if (socket == null) {
            return true;
        }
        try {
            socket.sendUrgentData(0);//发送1个字节的紧急数据，默认情况下，服务器端没有开启紧急数据处理，不影响正常通信
            return false;
        } catch (Exception se) {
            return true;
        }
    }

    private String getIP() {
        return FileUtil.getInstance().reloadSetting().ip;
    }
}
